import React from "react";
import SdkStore from "./sdkstore";
import { autorun } from "mobx";
import moment from "moment";
import { resolveMsgFormContent } from "../utils/index";
import { ChangeMessagesStatus, CustomDataType, MessageDataChangeType, ConversationType, ContentType } from '../constants';
export const mySdkStore = new SdkStore();


const isMatch = (id, msgIds) => !!msgIds.find((mid) => mid === id);

const changeMsgStatusInMsgListFromCursor = (cursorMsgId, statusKey, messageList) => {
  const cursorIndex = messageList.findIndex(m => m.msgId === cursorMsgId);
  if(cursorIndex < 0) return
  const newMsgList = [...messageList];
  newMsgList.forEach((m, idx) => {
    if(cursorIndex >= idx) {
      const newMsg = {...m};
      newMsg[statusKey] = true;
      newMsgList[idx] = newMsg;
    }
  });
  mySdkStore.updateCurrentMessageList([...newMsgList]);
}

const changeMsgStatusInMsgList = (messageData) => {
  const { msgIds, readStatusInfosList, readStatusInfo } = messageData;
  if(msgIds) {
    const newMessageList = [...mySdkStore.currentMessageList].map((item) => {
      if (isMatch(item.msgId, msgIds)) {
        if (messageData.msgStateChangeType === ChangeMessagesStatus.Read) {
          let matchRvo = readStatusInfo || {};
          if (readStatusInfosList && readStatusInfosList.length) {
            matchRvo = readStatusInfosList.find( rvo => rvo.messageId === item.msgId, );
          }
          if(item.readStatusVO) {
            item.readStatusVO.unReadUserCount = matchRvo.totalUnReadUserCount
          }else{
            item.readStatusVO = { unReadUserCount: matchRvo.totalUnReadUserCount };
          }
          item.isRead = true;
        }else if (messageData.msgStateChangeType === ChangeMessagesStatus.Recall) {
          item.isRecall = true;
        }else if (messageData.msgStateChangeType === ChangeMessagesStatus.Delete) {
          item.isDelete = true;
        }
      }
      return item;
    });
    mySdkStore.updateCurrentMessageList([...newMessageList]);
  }else if(messageData.msgStateChangeType === "deleteFromCursor") {
    const { cursorMsgId } = messageData;
    changeMsgStatusInMsgListFromCursor(cursorMsgId, 'isDelete', mySdkStore.currentMessageList);
  }else if(messageData.msgStateChangeType === "readFromCursor") {
    const { cursorMsgId } = messageData;
    changeMsgStatusInMsgListFromCursor(cursorMsgId, 'isRead', mySdkStore.currentMessageList);
  }
}

const changeMsgStatusInConverList = (messageData) => {
  const { cid } = messageData;
  const newConverList = [...mySdkStore.converList];
  const matchIndex = newConverList.findIndex((conver) => conver.cid === cid);
  if (matchIndex >= 0) {
    mySdkStore.sdk.querySingleConversation({ cid }).then(converDetail => {
      const { gmtCreate, lastMsgContentType, lastMsgContent, lastMsgSenderId, lastMsgRecallStatus, unReadCount } = converDetail;
      const matchConver = {...newConverList[matchIndex]}
      const isFromSelf = lastMsgSenderId === mySdkStore.mockConfig.userId;
      const lastMsg = lastMsgRecallStatus > 0
          ? `${ isFromSelf ? "你" : "对方" }撤回了一条消息`
          : resolveMsgFormContent(lastMsgContentType, lastMsgContent);
  
      Object.assign(matchConver, {
        ...matchConver,
        unReadCount,
        gmtCreate: moment(gmtCreate).format("YYYY/MM/DD HH:mm:ss"),
        lastMsg,
      });
      newConverList[matchIndex] = matchConver;
      mySdkStore.updateConverList(newConverList);
    })
  }
}

autorun(() => {
    console.log("new mySdkStore sdk>>>", mySdkStore.sdk);
    if(mySdkStore.sdk) {
      mySdkStore.sdk.onMsgStatusChange = (messageData) => {
        console.log('onMsgStatusChange data>>>', messageData);
        if(mySdkStore.currentMessageList.length){
          changeMsgStatusInMsgList(messageData);
        };
        if(mySdkStore.converList.length) {
          changeMsgStatusInConverList(messageData);
        }
      }

      mySdkStore.sdk.onMsgDataChange = (changeData) => {
        const { msgId, type, data } = changeData;
        const newMsgList = [...mySdkStore.currentMessageList];
        const matchIndex = newMsgList.findIndex( (msg) => msg.msgId === msgId );
        if(matchIndex >= 0) {
          const matchItem = newMsgList[matchIndex];
          if (type === MessageDataChangeType.AddInstantReplyFace) {
            if(Array.isArray(matchItem.instantReplyFaceInfos) && matchItem.instantReplyFaceInfos?.length) {
              matchItem.instantReplyFaceInfos.push(data);
            }else{
              matchItem.instantReplyFaceInfos = [data];
            }
            newMsgList[matchIndex] = {...matchItem};
          }else if(type === MessageDataChangeType.RecallInstantReplyFace) {
            if(Array.isArray(matchItem.instantReplyFaceInfos) && matchItem.instantReplyFaceInfos?.length) {
              const newInstantReplyFaceInfos = [...matchItem.instantReplyFaceInfos];
              const matchRecallinedx = newInstantReplyFaceInfos.findIndex(f => f.faceContent.iconId === data.iconId);
              if(matchRecallinedx >= 0) {
                newInstantReplyFaceInfos.splice(matchRecallinedx, 1);
                matchItem.instantReplyFaceInfos = newInstantReplyFaceInfos;
                newMsgList[matchIndex] = {...matchItem};
              }
            }
          }
          mySdkStore.updateCurrentMessageList(newMsgList);
        }
      }

      mySdkStore.sdk.onNewMessage = (msgs) => {
        console.log('onNewMessage>>>', msgs);
        const lastInNewMsgs = msgs[msgs.length - 1];
        const { cid, msgType, msgContent, msgId, from } = lastInNewMsgs;
        
        const newConverList = [...mySdkStore.converList];
        const matchIndex = newConverList.findIndex((conver) => conver.cid === cid);
        if (matchIndex >= 0) {
          const matchConver = {...newConverList[matchIndex]};
          const { unReadCount, bizParams } = matchConver;
          const isFromSelf = from?.userId === mySdkStore.mockConfig.userId
          const newLastMsg = resolveMsgFormContent(msgType, msgContent);
          let calcuUnReadCount = unReadCount;


          // mySdkStore.sdk.changeMessagesStatus({cid, type: 'delete', msgIds: msgs }).then(data => {
          //   console.warn('新消息删除', data);
          // });
          if(cid === mySdkStore.inChatCid) {
            // 如果视图层正处于某个会话的聊天界面中，更新currentMessageList，并设置新消息已读
            const newMessageList = msgs.filter(item => item.cid === cid);
            if(newMessageList.length) {
              mySdkStore.updateCurrentMessageList([...mySdkStore.currentMessageList, ...newMessageList]);
              mySdkStore.sdk.changeMessagesStatus({cid, type: 'read', msgIds: newMessageList }).then(data => {
                console.warn('新消息已读受理', data);
              });
            }
          }else if ( !bizParams.is_default_read && !isFromSelf ) {
            calcuUnReadCount = unReadCount + msgs.length;
          }

          //处理消息所属会话的未读数、最后一条消息、变更时间
          Object.assign(matchConver, {
            unReadCount: calcuUnReadCount,
            lastMsgId: msgId,
            lastMsgContentType: msgType,
            lastMsg: newLastMsg,
            gmtModified: new Date().valueOf(),
          })

          //如果是已隐藏会话，收到新消息时取消隐藏状态，并像服务器发送变更
          matchConver.bizParams = Object.assign({}, bizParams, {is_hidden: "0"});
          if (bizParams.is_hidden === "1") {
            mySdkStore.sdk.addConversationUserMark({
              cid,
              marks: [{ propertyName: "is_hidden", propertyValue: 0 }],
            });
          }

          newConverList[matchIndex] = matchConver;
          //更新会话
          mySdkStore.updateConverList(newConverList);
        }
        
        //更新全局消息数据
        mySdkStore.setNewMessageData(msgs);
        mySdkStore.setNewMessageTopBarProps({
          visible: true,
          ...msgs[0]
        });
      };

      mySdkStore.sdk.onConverChange = (res) => {
        const { cid, changeType } = res;
        console.log('onConverChange >>>', res);
        if(changeType === 'addNewConver' && res.creator && (res.creator !== mySdkStore.mockConfig.userId)) {
          mySdkStore.sdk.querySingleConversation({ cid }).then( data => {
            const { type, creator, memberCount } = data;
            if((creator !== mySdkStore.mockConfig.userId) && type === "meeting") {
              mySdkStore.setCurrentMeetingInfo({ cid, memberCount });
            }else{
              const newConverList = [...mySdkStore.converList];
              newConverList.push(data);
              mySdkStore.updateConverList(newConverList);
            }
          })
        }else if(changeType === 'closeConver') {
          const newConverList = [...mySdkStore.converList];
          const matchIndex = newConverList.findIndex((conver) => conver.cid === cid);
          if(matchIndex > -1) {
            newConverList.splice(matchIndex, 1);
            mySdkStore.updateConverList(newConverList);
          }
        }
      };

      mySdkStore.sdk.onGroupInfoChange = (updateGroupRepones) => {
        console.log('onGroupInfoChange >>>', updateGroupRepones);
        const { cid, updateType, name, logoUrl } = updateGroupRepones;
        const newConverList = [...mySdkStore.converList];
        const matchIndex = newConverList.findIndex(
          (conver) => conver.cid === cid
        );
        if (matchIndex > -1) {
          const matchItem = newConverList[matchIndex];
          if (updateType === "name") {
            newConverList[matchIndex] = { ...matchItem, name, sessionName: name };
          } else if (updateType === "logo") {
            newConverList[matchIndex] = { ...matchItem, logoUrl };
          }
        }
        mySdkStore.updateConverList([...newConverList]);
      };
    }
});


export const MySdkStoreContext = React.createContext(mySdkStore);